package com.bestillet.kyllingogco;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.AsyncTask.Status;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class BasketActivity extends Activity {
	private ArrayList<ImageTask> tasks;
	private ArrayList<Item> basket;
	private ArrayList<Card> cards;

	private SharedPreferences preferences;
	private Button order, back, home;
	private ListView list;
	private TextView total;
	private Activity activity;
	
	private ShopApplication app;
	private LoadingDialog loading;
	private BasketTask task;
	
	private boolean copied;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.basket);
		
		activity = this;
		tasks = new ArrayList<ImageTask>();
		
		copied = getIntent().getBooleanExtra("copied", false);
		
		preferences = getSharedPreferences("Kylling & Co", MODE_PRIVATE);
		app = (ShopApplication) getApplicationContext();
		cards = app.getCards();
		
		order = (Button) findViewById(R.id.btnOrder);
		order.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (app.getShop().getHours().equals("Lukket") || app.getShop().getOrders().equals("Lukket")) {
					Toast.makeText(v.getContext(), R.string.error_closed, Toast.LENGTH_LONG).show();
					return;
				}
				try {
					String[] early = app.getShop().getOrders().split("-")[0].split(":");
					String[] late = app.getShop().getOrders().split("-")[1].split(":");
					int eh = Integer.parseInt(early[0]);
					int em = Integer.parseInt(early[1]);
					int lh = Integer.parseInt(late[0]);
					int lm = Integer.parseInt(late[1]);
					
					Calendar calendar = Calendar.getInstance();
					float now = calendar.getTimeInMillis();
					
					calendar.set(Calendar.HOUR_OF_DAY, eh);
					calendar.set(Calendar.MINUTE, em);
					if (calendar.getTimeInMillis() - now > 0) {
						dialog();
						return;
					}
					
					calendar.set(Calendar.HOUR_OF_DAY, lh);
					calendar.set(Calendar.MINUTE, lm);
					if (calendar.getTimeInMillis() - now <= 0) {
						dialog();
						return;
					}
				} catch (NumberFormatException e) { }
				
				if (basket.size() > 0) {
					int sandwiches = 0;
					for (int i = 0; i < basket.size(); i++) {
						if (basket.get(i).getCategoryId() == 1) {
							sandwiches += basket.get(i).getAmount();
						}
					}
					
					Intent intent = new Intent(v.getContext(), CheckoutActivity.class);
					intent.putExtra("sandwiches", sandwiches);
					intent.putExtra("copied", copied);
					startActivity(intent);
				} else {
					Toast.makeText(v.getContext(), R.string.error_empty, Toast.LENGTH_LONG).show();
				}
			}
		});
		
		back = (Button) findViewById(R.id.btnBasketBack);
		back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (copied) {
					finish();
				} else {
					Intent intent = new Intent(v.getContext(), CategoryActivity.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
				}
			}
		});
		
		home = (Button) findViewById(R.id.btnBasketHome);
		home.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (copied) {
					finish();
				} else {
					Intent intent = new Intent(v.getContext(), CategoryActivity.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
				}
			}
		});

		total = (TextView) findViewById(R.id.lblTotal);
		list = (ListView) findViewById(android.R.id.list);
		list.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
				if (basket.get(position).getIdx() > 0) {
					RemoveDialog remove = new RemoveDialog(v.getContext(), basket.get(position), position, app.getShop().getIdx(), app.getBasketId());
					remove.show();
				}
			}
		});
		
		loading = new LoadingDialog(activity);
		loading.show();
		
		task = new BasketTask();
		task.execute();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		
		while (tasks.size() > 0) {
			if (tasks.get(0).getStatus() == Status.RUNNING) {
				tasks.get(0).cancel(true);
				tasks.remove(0);
			}
		}
		
		if (task != null)
			if (task.getStatus() == Status.RUNNING)
				task.cancel(true);
		
		if (basket != null)
			basket.clear();
	}
	
	public void total() {
		int price = 0;
		for (Item item : basket) {
			int temp = item.getPrice();
			price += temp * item.getAmount();
		}
		total.setText(" " + price + ",-");
	}
	
	@Override
	public void onBackPressed() {
		if (copied) {
			finish();
		} else {
			Intent intent = new Intent(this, CategoryActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
		}
	}
	
	public void onItemRemoved(int index) {
		/*basket.remove(index);
		list.invalidateViews();
		total();*/
		
		loading = new LoadingDialog(activity);
		loading.show();
		
		task = new BasketTask();
		task.execute();
	}

	@Override
	public boolean onCreateOptionsMenu(android.view.Menu menu) {
		menu.add(android.view.Menu.NONE, -2, 0, "Info");
		menu.add(android.view.Menu.NONE, -1, 0, "Indstillinger");
		menu.add(android.view.Menu.NONE, 0, 0, "Tidligere ordrer");
		for (int i = 0; i < cards.size(); i++)
			menu.add(android.view.Menu.NONE, cards.get(i).getIdx(), cards.get(i).getPosition() + 1, cards.get(i).getName());
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case -2:
			Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://m.kyllingogco.dk/kontakt.asp?shopid=" + app.getShop().getIdx()));
			startActivity(browserIntent);
			break;
		case -1:
			Intent customer = new Intent(this, CustomerActivity.class);
			startActivity(customer);
			break;
		case 0:
			Intent order = new Intent(this, OrderActivity.class);
			startActivity(order);
			break;
		default:
			Intent card = new Intent(this, CardActivity.class);
			card.putExtra("idx", item.getItemId());
			card.putExtra("title", item.getTitle());
			startActivity(card);
			break;
		}
    	return true;
	}
	
	private void dialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(activity);
		builder.setMessage(getResources().getString(R.string.main_open) + " " + app.getShop().getOrders())
				.setTitle(R.string.error_closed)
				.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) { }
				});
		AlertDialog dialog = builder.create();
		dialog.show();
	}
	
	private class BasketTask extends AsyncTask<Void, Void, Boolean> {
		@Override
		protected Boolean doInBackground(Void... params) {
			try {
				InputStream in = Server.post(Server.BASKET, Server.getBasketXml(app.getShop().getIdx(), app.getBasketId(), preferences.getString("phone", "")));
				XmlPullParser parser = Server.toXmlParser(in);
				basket = XmlParser.getBasket(parser);
			} catch (IOException e) {
				Log.e("Shop", "IOException: " + e.getMessage());
				return false;
			} catch (XmlPullParserException e) {
				Log.e("Shop", "XmlPullParserException: " + e.getMessage());
				return false;
			} catch (NullPointerException e) {
    			Log.e("Shop", "NullPointerException: " + e.getMessage());
				return false;
			} catch (IllegalArgumentException e) {
    			Log.e("Shop", "IllegalArgumentException: " + e.getMessage());
    			return false;
    		}
			return true;
		}
		
		@Override
	    protected void onPostExecute(Boolean success) {
			if (success) {
				for (int i = 0; i < basket.size(); i++) {
    				Bitmap b = app.getBitmapFromMemCache(basket.get(i).getPicturenormal());
    				if (b != null) {
    					if (b.isRecycled()) {
    						app.removeBitmapFromMemoryCache(basket.get(i).getPicturenormal());
    	    				ImageTask it = new ImageTask();
    	    				it.execute(i);
    	    				tasks.add(it);
    					} else {
    						basket.get(i).setImage(b);
    					}
    				} else {
	    				ImageTask it = new ImageTask();
	    				it.execute(i);
	    				tasks.add(it);
    				}
    			}
				
				total();
				BasketArrayAdapter adapter = new BasketArrayAdapter(activity, basket);
				list.setAdapter(adapter);
			} else {
				AlertDialog.Builder builder = new AlertDialog.Builder(activity);
	    		builder.setMessage(R.string.error_basket)
	    		       .setTitle(R.string.error)
	    		       .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								task = new BasketTask();
								task.execute();
								loading.show();
							}
						})
						.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								finish();
							}
						});
	    		AlertDialog dialog = builder.create();
	    		dialog.show();
			}
			loading.dismiss();
		}
	}
	
	private class ImageTask extends AsyncTask<Integer, Void, Boolean> {
		private Bitmap b;
		private int index;
		
    	@Override
		protected Boolean doInBackground(Integer... params) {
    		try {
    			index = params[0];
    			Item item = basket.get(index);
    			InputStream in = Server.get(Server.PRODUCT_IMAGES + item.getPicturenormal());
    			b = Server.downloadBitmap(in, activity);
    			in.close();
    			item.setImage(b);
    			app.addBitmapToMemoryCache(basket.get(index).getPicturenormal(), b);
			} catch (IOException e) {
    			Log.e("Shop", "IOException: " + e.getMessage());
				return false;
			} catch (NullPointerException e) {
    			Log.e("Shop", "NullPointerException: " + e.getMessage());
				return false;
			} catch (OutOfMemoryError e) {
    			Log.e("Shop", "OutOfMemoryError: " + e.getMessage());
				return false;
			}
    		return true;
    	}
    
	    @Override
	    protected void onPostExecute(Boolean success) {
	    	if (success) {
    			runOnUiThread(new Runnable() {
    				@Override
    				public void run() {
    					try {
	    	    			View v = list.getChildAt(index);
	    	    			ImageView image = (ImageView) v.findViewById(R.id.imgItemImage);
	    	    			image.setImageBitmap(b);
    					} catch (NullPointerException e) {
    						Log.e("Shop", "NullPointerException: " + e.getMessage());
    					}
    				}
    			});
	    	}
			tasks.remove(this);
	    }
	}
}